package com.tyc.shiro.oauth2;

import com.tyc.shiro.controller.SysController;
import com.tyc.shiro.entity.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 认证
 *
 * @author tyc
 * @version 1.0
 * @date 2023-12-21 15:26:31
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    /**
     * 第一步
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 认证
     * 第二步：校验 token，成功后将用户信息返回
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户标识：token
        String accessToken = (String) token.getPrincipal();
        // todo 校验 token：非空判断，过期判断
        // todo 根据 token 在数据库中对应的 userId 获取到用户信息
        SysUser sysUser = SysController.getSysUser("admin");
        if(sysUser.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        return new SimpleAuthenticationInfo(sysUser,accessToken,getName());
    }


    /**
     * 授权
     * 当资源需要验证权限时调用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
        Long userId = sysUser.getId();
        // todo 根据用户 id 从数据库获取角色与权限列表
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 设置角色
        info.setRoles(getRoles(userId));
        // 设置权限
        info.setStringPermissions(getPerms(userId));
        return info;
    }

    public Set<String> getPerms(Long userId){
        if(1 != userId){
            return null;
        }
        Set<String> set = new HashSet<>();
        set.add("secure:add");
        set.add("secure:edit");
        set.add("edit");
        set.add("del");
        return set;
    }

    public Set<String> getRoles(Long userId){
        if(1 != userId){
            return null;
        }
        Set<String> set = new HashSet<>();
        set.add("user");
        set.add("admin");
        set.add("test");
        return set;
    }


}
